<template>
    <div class="business">
        <div class="header" v-show="showHeader">
            <el-form :inline="true" :model="queryInfo" class="demo-form-inline">
                <el-form-item label="客户名称">
                    <el-input v-model="queryInfo.name" placeholder="请输入客户姓名" clearable />
                </el-form-item>
                <el-form-item label="客户手机">
                    <el-input v-model="queryInfo.phone" placeholder="请输入客户手机" clearable />
                </el-form-item>
                <el-form-item label="归属人">
                    <el-input v-model="queryInfo.owner" placeholder="请输入归属人" clearable />
                </el-form-item>
                <el-form-item label="跟进时间">
                    <el-date-picker v-model="queryInfo.createTime" type="datetimerange" start-placeholder="开始时间"
                        end-placeholder="结束时间" range-separator="-" format="YYYY-MM-DD HH:mm:ss"
                        date-format="YYYY/MM/DD ddd" time-format="A hh:mm:ss" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="findBusinessList"> <el-icon>
                            <Search />
                        </el-icon>搜索</el-button>
                    <el-button class="addBtn" @click="resetForm"> <el-icon>
                            <Refresh />
                        </el-icon>重置</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div class="nav">
            <div class="l">
                <el-button type="primary" plain @click="openUserDialog"><el-icon>
                        <Plus />
                    </el-icon>新增</el-button>
                <el-button v-if="selectedActivities.length == 0" disabled type="success" plain
                    @click="openDialog"><el-icon>
                        <Edit />
                    </el-icon>修改</el-button>
                <el-button v-else type="success" plain @click="openDialog"><el-icon>
                        <Edit />
                    </el-icon>修改</el-button>
                <el-button v-if="selectedActivities.length == 0" disabled type="danger" plain
                    @click="deleteActivityAll"><el-icon>
                        <Delete />
                    </el-icon>删除</el-button>
                <el-button v-else type="danger" plain @click="deleteActivityAll"><el-icon>
                        <Delete />
                    </el-icon>删除</el-button>
                <el-button type="warning" plain @click="exportToExcel"><el-icon>
                        <Download />
                    </el-icon>导出</el-button>
            </div>
            <div class="r">
                <el-button :icon="Search" circle @click="showHeader = !showHeader" />
                <el-button :icon="Refresh" circle @click="setPage(1)" />
            </div>
        </div>
        <div class="toBe">
            <el-table :data="business" style="width: 100%" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" />
                <el-table-column prop="name" label="客户姓名" />
                <el-table-column prop="phone" label="手机号码" />
                <el-table-column prop="owner" label="商机归属" />
                <el-table-column prop="createTime" label="创建时间" />
                <el-table-column label="商机状态">
                    <template #default="scope">
                        <el-tag type="danger" v-if="scope.row.status == 0">未知状态</el-tag>
                        <el-tag type="primary" v-else-if="scope.row.status == 1">已分配</el-tag>
                        <el-tag type="success" v-else-if="scope.row.status == 2">进行中</el-tag>
                        <el-tag type="info" v-else>回收</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="nextTime" label="下次跟进时间" />
                <el-table-column label="操作" min-width="150" align="center">
                    <template #default="scope">
                        <span class="l" @click="goDetail(scope.row.businessId)"><el-icon>
                                <View />
                            </el-icon>查看</span>
                        <span class="r" v-if="scope.row.status == 1" @click="assignFind(scope.row.businessId)"><el-icon>
                                <Pointer />
                            </el-icon>分配</span>
                        <span class="r" v-if="scope.row.status == 1 || scope.row.status == 2"
                            @click="goDetail2(scope.row.businessId)"><el-icon>
                                <TopRight />
                            </el-icon>跟进</span>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <Pagination :total="total" @changePage="setPage" @changeRows="setRows"></Pagination>
        <el-dialog v-model="dialogVisible" :title="id ? '修改商机' : '添加商机'" width="750" :before-close="handleClose">
            <el-form :inline="true" ref="businessFormRef" :model="businessForm" :rules="rules" label-width="auto"
                class="demo-ruleForm" :size="formSize" status-icon>
                <el-form-item label="手机号码" prop="phone">
                    <el-input v-model="businessForm.phone" placeholder="请输入手机号码" />
                </el-form-item>
                <el-form-item label="客户姓名" prop="name">
                    <el-input v-model="businessForm.name" placeholder="请输入客户名称" />
                </el-form-item>
                <el-form-item label="渠道来源" prop="channelId">
                    <el-select v-model="businessForm.channelId" clearable placeholder="请选择渠道" @click="getChannelList">
                        <el-option v-for="item in channel" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="活动信息" prop="channelId">
                    <el-select v-model="businessForm.activityId" clearable placeholder="请选择信息" @click="getActivityList">
                        <el-option v-for="item in activity" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="客户性别" prop="gender">
                    <el-radio-group v-model="businessForm.gender">
                        <el-radio :label="1">男</el-radio>
                        <el-radio :label="2">女</el-radio>
                        <el-radio :label="3">未知</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="客户年龄" prop="age">
                    <el-input-number v-model="businessForm.age" />
                </el-form-item>
                <el-form-item label="微信号" prop="weixin">
                    <el-input v-model="businessForm.weixin" placeholder="请输入微信号码" />
                </el-form-item>
                <el-form-item label="QQ号码" prop="qq">
                    <el-input v-model="businessForm.qq" placeholder="请输入QQ号码" />
                </el-form-item>
                <el-form-item>
                    <el-button v-if="id" type="primary" @click="editActivityForm(businessFormRef)">编辑</el-button>
                    <el-button v-else type="success" @click="addActivityForm(businessFormRef)">添加</el-button>
                    <el-button @click="dialogVisible = false">取消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
        <el-dialog v-model="dialogVisible1" title="分配商机" width="800" :before-close="handleClose">
            <el-form :inline="true" ref="assignFormRef" :model="assignForm" :rules="rules" label-width="auto"
                class="demo-ruleForm" :size="formSize" status-icon>
                <el-form-item label="归属部门" prop="phone">
                    <el-tree-select v-model="assignForm.departmentId" :data="transformedData"
                        :render-after-expand="true" check-strictly=true style="width: 240px" placeholder="请选择归属部门"
                        @change="getArea" />
                </el-form-item>
                <el-form-item label="分配给" prop="name">
                    <el-select value-key="id" @change="searchSelect" v-model="oldWorld" clearable placeholder="请选择用户">
                        <el-option v-for="item in genderOption" :key="item.id" :label="item.nickName" :value="item" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="changeUser()">确定</el-button>
                    <el-button @click="dialogVisible1 = false">取消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import {
    Refresh,
    Search,
} from '@element-plus/icons-vue'
import { onMounted, reactive, ref, watch } from 'vue';
import { BusinessListget, addBusiness, BusinessData, editBusiness, BusinessDelete, findBusiness, expostBusiness, BusinessChannelList, BusinessActivityList, activityList, BusinessTreeselect, BusinessUser, BusinessAssignment } from "../../../api/index"
import { ComponentSize, ElMessage, ElMessageBox, FormInstance, FormRules } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
import Pagination from '../Pagination.vue';
import * as XLSX from 'xlsx';
const showHeader = ref(true)
const assignFormRef = ref<FormInstance>()
const thisAssignId = ref(0)
const assignForm = ref({
    deptId: 0,
    type: 1,
    userId: 0,
    userName: "",
    nickName: "",
    departmentId: "",
    assignId: 0
})
const searchSelect = (val) => {
    assignForm.value.deptId = val.deptId
    assignForm.value.userId = val.userId
    assignForm.value.userName = val.userName
    assignForm.value.nickName = val.nickName
}
const oldWorld = ref("")
const handleId = ref(0)
const transformedData = ref([]);
const genderOption = ref([])
const getArea = () => {
    handleId.value = assignForm.value.departmentId;
    BusinessUser(handleId.value).then((res: any) => {
        genderOption.value = res.data.data
    }).catch((error: any) => {
        console.error("Error fetching user data:", error);
    });
}
const changeUser = () => {
    assignForm.value.assignId = thisAssignId.value
    BusinessAssignment(assignForm.value).then((res: any) => {
        ElMessage({
            message: res.data.msg,
            type: 'success'
        })
        dialogVisible1.value = false
        getBusinessList()
    }).catch((error: any) => {
        console.error("Error fetching user data:", error);
    });
}
const areaOptions = ref([])
const assignFind = (id) => {
    assignForm.value.deptId = 0
    assignForm.value.type = 1
    assignForm.value.userId = 0
    assignForm.value.departmentId = ""
    assignForm.value.nickName = ""
    assignForm.value.userName = ""
    oldWorld.value = ""
    thisAssignId.value = id
    BusinessTreeselect().then((res: any) => {
        const rawData = res.data.data
        transformedData.value = transformData(rawData);
    })
    dialogVisible1.value = true
}
function transformData(data) {
    return data.map(item => {
        const newItem = { ...item };
        newItem.value = newItem.id;
        delete newItem.id;
        if (newItem.children) {
            newItem.children = transformData(newItem.children);
        }
        return newItem;
    });
}

const newWorld = ref({
    pageNum: 1,
    pageSize: 10,
})
// 分页器返回参数 通过自定义事件
const setPage = (n: number) => {
    newWorld.value.pageNum = n;
    getBusinessList();
};
const setRows = (n: number) => {
    newWorld.value.pageSize = n;
    getBusinessList();
};
const exportToExcel = () => {
    // 创建一个工作簿
    const workbook = XLSX.utils.book_new();

    // 创建一个工作表
    const data = business.value.map(item => [
        item.name,
        item.nextTime,
        item.status === 0 ? "未分配" : "已分配",
        item.owner,
        item.createTime
    ]);
    const worksheet = XLSX.utils.aoa_to_sheet(data);

    // 将工作表添加到工作簿
    XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');

    // 生成Excel文件
    XLSX.writeFile(workbook, 'data.xlsx');
};
const router = useRouter();
const route = useRoute();
const formSize = ref<ComponentSize>("default");
const businessFormRef = ref<FormInstance>();
const businessForm = reactive({
    businessId: 0,
    name: '',
    phone: '',
    gender: 1,
    weixin: '',
    qq: '',
    age: 0,
    channelId: "",
    activityId: "",
});
const id = ref(0);

import { formdata } from "../../../utils/format"
import { status } from 'nprogress';
import { Phone } from '@element-plus/icons-vue';
import bus from '../../../../../14_Vue3/adminsystem/src/utils/bus';

// watch(() => businessForm.fundTimeArray, (newVal) => {
//     console.log(newVal)
//     const formatTimeArray = ref([])
//     newVal.forEach(el => {
//         // console.log(el)
//         formatTimeArray.value.push(formdata.formDate(el))
//         businessForm.beginTime = formatTimeArray.value[0]
//         businessForm.endTime = formatTimeArray.value[1]
//     });
// })
const rules = reactive<FormRules>({
    name: [{ required: true, message: "请输入客户姓名", trigger: "blur" }],
    phone: [{ required: true, message: "请输入手机号码", trigger: "blur" }],
});
const businessId = ref('')
const dialogVisible = ref(false)
const dialogVisible1 = ref(false)
const value = ref('')
const value1 = ref('')
const value2 = ref('')
const options1 = [
    {
        value: '1',
        label: '正常',
    },
    {
        value: '0',
        label: '禁用',
    }
]
const options2 = [
    {
        value: '2',
        label: '线下商机',
    },
    {
        value: '1',
        label: '线上商机',
    }
]
const queryInfo = ref({
    name: "",
    phone: "",
    owner: "",
    createTime: ""
});
const channel = ref([])
const activity = ref([])
const business = ref([]);
const selectedActivities = ref([])

const goDetail = (data: any) => {
    router.push({ path: '/business/businessDetail2', query: { id: data } })
}
const goDetail2 = (data: any) => {
    router.push({ path: '/business/businessDetail', query: { id: data } })
}
const openDialog1 = () => {
    dialogVisible1.value = true
}
const openDialog = () => {
    id.value = getSubstringBeforeComma(getSelectedBusinessIds());
    console.log(id.value)
    BusinessData(id.value).then(res => {
        Object.entries(res.data.data).map((item) => {
            businessForm[item[0]] = item[1];
        })
    })
    dialogVisible.value = true
    businessForm.businessId = id.value
}
const resetForm = () => {
    queryInfo.value.name = ""
    queryInfo.value.phone = ''
    queryInfo.value.createTime = ''
    queryInfo.value.owner = ''
};
const openUserDialog = () => {
    id.value = 0;
    dialogVisible.value = true
    businessForm.businessId = 0
    businessForm.name = ""
    businessForm.weixin = ''
    businessForm.qq = ''
    businessForm.age = 0
    businessForm.phone = ""
    businessForm.gender = 1
    businessForm.channelId = ""
    businessForm.activityId = ""
}
const getChannelList = () => {
    BusinessChannelList().then((res: any) => {
        if (res.data.code != 200) return ElMessage.error("查询渠道失败");
        channel.value = res.data.data.map(item => ({
            value: Number(item.channelId),
            label: item.channelName
        }));
    });
}


const getActivityList = () => {
    const data = businessForm.channelId
    BusinessActivityList(data).then((res: any) => {
        if (res.data.code != 200) return ElMessage.error("查询活动失败");
        activity.value = res.data.data.map(item => ({
            value: Number(item.activityId),
            label: item.name
        }));
    });
}
const addActivityForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
        if (valid) {
            addBusiness(businessForm).then((res: any) => {
                if (res.data.code != 200) return ElMessage.error("添加商机失败");
                ElMessage.success("添加商机成功");
                getBusinessList();
                dialogVisible.value = false
            });
        } else {
            console.log("error submit!", fields);
        }
    });
};
const deleteActivityAll = () => {
    const ids = getSelectedBusinessIds()
    const Names = getSelectedBusinessNames()
    ElMessageBox.confirm("是否确认删除客户姓名为'" + Names + "'的数据项?", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
    })
        .then(() => {
            BusinessDelete(ids).then((res: any) => {
                if (res.data.code != 200) return ElMessage.error("删除商机失败");
                ElMessage.success("删除商机成功");
                getBusinessList();
            });
        })
        .catch(() => {
            ElMessage.info("取消删除");
        });

};
const businessExport = () => {
    expostBusiness().then((res: any) => {
        if (res.data.code != 200) return ElMessage.error("导出商机失败");
        ElMessage.success("导出商机成功");
    });
}
const handleDelete = (data: any) => {
    ElMessageBox.confirm("是否确认删除商机编号为" + data + "的数据项?", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
    })
        .then(() => {
            BusinessDelete(data).then((res: any) => {
                if (res.data.code != 200) return ElMessage.error("删除商机失败");
                ElMessage.success("删除商机成功");
                getBusinessList();
            });
        })
        .catch(() => {
            ElMessage.info("取消删除");
        });
}
const editActivityForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
        if (valid) {
            businessForm.createTime = ""
            businessForm.updateTime = ""
            editBusiness(businessForm).then((res: any) => {
                if (res.data.code != 200) return ElMessage.error("修改商机失败");
                ElMessage.success("修改商机成功");
                getBusinessList();
                dialogVisible.value = false
            });
        } else {
            console.log("error submit!", fields);
        }
    });
};
const findActivityList = () => {
    findBusiness(queryInfo).then((res: any) => {
        if (res.data.code != 200) return ElMessage.error("查询商机失败");
        business.value = res.data.rows;
    });
}
const total = ref(0);
const getBusinessList = () => {
    findBusiness(newWorld.value).then((res: any) => {
        if (res.data.code != 200) return ElMessage.error("查询商机失败");
        business.value = res.data.rows;
        total.value = res.data.total;
    });
}
const findBusinessList = () => {
    findBusiness(queryInfo.value).then((res: any) => {
        if (res.data.code != 200) return ElMessage.error("查询商机失败");
        business.value = res.data.rows;
    });
}
function getSubstringBeforeComma(str) {
    const index = str.indexOf(',');
    if (index === -1) {
        return str;
    }
    return str.substring(0, index);
}
const handleSelectionChange = (selection) => {
    selectedActivities.value = selection;
}
const getSelectedBusinessIds = () => {
    const businessIds = selectedActivities.value.map(item => item.businessId);
    return businessIds.join(',');
}

const getSelectedBusinessNames = () => {
    const businessIds = selectedActivities.value.map(item => item.name);
    return businessIds.join(',');
}
const handleClose = (done: () => void) => {
    done()
}
onMounted(() => {
    getBusinessList();
})
</script>

<style scoped lang="scss">
.business {
    width: 100%;
    height: 100%;
    padding: 20px;

    .header {

        i {
            margin-right: 10px;
        }
    }

    .nav {
        margin-bottom: 10px;
        display: flex;
        align-items: center;
        justify-content: space-between;

        i {
            margin-right: 10px;
        }
    }

    .toBe {
        margin-bottom: 20px;

        .l,
        .r {
            color: #409dfe;
            cursor: pointer;
            display: inline-block;

            i {
                padding-top: 4px;
            }
        }

        .r {
            margin-left: 10px;
        }
    }
}

.el-upload__tip {
    height: 150px;
    display: flex;
    align-items: center;
    justify-content: center;

    div {
        text-align: center;
    }

    em {
        color: #409dfe;
    }
}
</style>